package com.rq.base.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rq.base.R;
import com.rq.base.net.RequestType;
import com.rq.base.reflect.activity.Fra_onHiddenChanged;
import com.rq.base.ui.impl.BaseView;
import com.rq.base.util.AppUtils;
import com.rq.base.util.LOG;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import static com.rq.base.ui.BaseController.TAG_PASS;
import static com.rq.base.ui.BaseController.TAG_PASS_DATA_SIZE;

public class BaseFragment<P extends BaseController> extends Fragment implements BaseView {
    protected P mPresenter;
    boolean isCreate = false;
    View fraRoot;

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        try {
            this.mPresenter = getController(this, 0);
        } catch (Exception e) {
            LOG.d("BaseFragment", "setArguments:" + e.getMessage());
        }
    }

    public static Bundle createBundle(Serializable... pass) {
        Bundle bundle = new Bundle();
        if (pass != null) {
            int index = -1;
            for (int i = 0; i < pass.length; i++) {
                if (pass[i] != null && pass[i].getClass().isArray()) {
                    Serializable[] obj = (Serializable[]) pass[i];
                    for (int i1 = 0; i1 < obj.length; i1++) {
                        if (index == -1) {
                            index = 0;
                        }
                        bundle.putSerializable(TAG_PASS + index, obj[index]);
                        index++;
                    }
                }
                if (index > 0) {
                    bundle.putSerializable(TAG_PASS + index, pass[i]);
                    index++;
                } else {
                    bundle.putSerializable(TAG_PASS + i, pass[i]);
                }
            }
            bundle.putInt(TAG_PASS_DATA_SIZE, pass.length);
        }
        return bundle;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //    mPresenter = getController(this, 0);
        LOG.e("BaseFragment", getStrTag() + ".BaseFragmentonCreate.isCloseAble:" + mPresenter);
        if (mPresenter != null) {
            if (mOperator != null) {
                mPresenter.setOperator(mOperator);
                LOG.e("BaseFragment", getStrTag() + ".BaseFragmentonCreate.41.isCloseAble:");
            }
            mPresenter.setFragment(this);
//      if (mPresenter.isImplements(BaseTabController.class) && OneFragmentShower.get() != null) {
//        LOG.e("BaseFragment", "BaseFragmentonCreate.takeOver:" + mPresenter.getClass()
//                                                                           .getSimpleName());
//        OneFragmentShower.get().takeOver(mPresenter, this);
//      } else {
//        LOG.e("BaseFragment", "BaseFragmentonCreate.not.takeOver:" + mPresenter.getClass()
//                                                                               .getSimpleName());
//      }
        }
    }

    @Nullable
    @Override
    public Activity getContext() {
        return getActivity();
    }

    @Override
    public <T> void onResponseSucceed(@NonNull RequestType type,
                                      @NonNull T data) {

    }

//    public void finishOK(Serializable... back) {
//        final Intent intent = new Intent();
//        if (back != null) {
//            LOG.d("BaseController", "finishOK.451:TAG_PASS");
//            for (int i = 0; i < back.length; i++) {
//                intent.putExtra(TAG_PASS + i, back[i]);
//            }
//            LOG.d("BaseController", "finishOK.TAG_PASS_DATA_SIZE:" + back.length);
//            intent.putExtra(TAG_PASS_DATA_SIZE, back.length);
//        }
//        if (popParentController != null) {
//            LOG.d("BaseController", "finishOK.onActivityResult:");
//            popParentController.onActivityResult(getInnerPassCode(), Activity.RESULT_OK, intent);
//            mPopupWindow.dismiss();
//            this.finish();
//            return;
//        }
//        if (controllerFinish()) {
//            return;
//        }
//        mActivity.setResult(Activity.RESULT_OK, intent);
//        mActivity.finish();
//    }
//
//    public void finish() {
//        LOG.showUserWhere("BaseController_finish");
//        LOG.d("BaseController", "finish.475:" + finishTime);
//        if (System.currentTimeMillis() - finishTime < 200) {
//            return;
//        }
//        this.isFinish = true;
//        finishTime = System.currentTimeMillis();
//        if (controllerFinish()) {
//            return;
//        }
//        mActivity.setResult(Activity.RESULT_CANCELED);
//        mActivity.finish();
//    }

    @Override
    public <T> void onResponseError(@NonNull RequestType type, @NonNull T data) {
    }

    @Override
    public void onConnectError(@NonNull RequestType type) {

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        LOG.e("BaseFragment", getStrTag() + ".onCreateView");
        if (fraRoot != null) {
            return fraRoot;
        }
        if (mPresenter != null) {
            fraRoot = mPresenter.inflateRootView(inflater, true);
            return fraRoot;
        }
        fraRoot = super.onCreateView(inflater, container, savedInstanceState);
        return fraRoot;
    }

    public boolean needTitleAndStatusBar() {
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mPresenter != null) {
            LOG.e("BaseFragment", "onActivityResult.91:" + mPresenter.getClass()
                    .getSimpleName() + ">>>" + mPresenter
                    .toString());
            if (mPresenter.onActivityResult(requestCode, resultCode, data)) {
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean isFirstShow = true;

    @Override
    public final void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (mPresenter instanceof Fra_onHiddenChanged) {
            ((Fra_onHiddenChanged) mPresenter).onHiddenChanged(hidden);
        }
        if (mPresenter != null && !hidden) {
            if (isFirstShow) {
                this.isFirstShow = false;
                mPresenter.onFraFirstShow();
            }
            LOG.e("BaseFragment", "onHiddenChanged.152:" + mPresenter.getClass().getSimpleName());
        }
        LOG.d("BaseFragment", "onHiddenChanged.onShowToUser:" + hidden);
        if (hidden) {
            onHideToUser();
        } else {
            onShowToUser();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LOG.d("BaseFragment", getStrTag() + ".onResume");
//    if (isCreate && OneFragmentShower.get() != null) {
//      LOG.d("BaseFragment", "onResume.onShowToUser:");
        onShowToUser();
//    } else {
//      isCreate = true;
//    }
    }

    @Override
    public void onPause() {
        super.onPause();
        LOG.e("BaseFragment", getStrTag() + ".onPause");
        onHideToUser();
    }

    protected void onHideToUser() {
        if (mPresenter != null) {
            LOG.e("BaseFragment", mPresenter.getClass().getSimpleName() + ".onHideToUser");
            CtrWatcher.get().removerFragmentController(mPresenter);
            CtrWatcher2.get().removerFragmentController(mPresenter);
            mPresenter.onControllerPause();
        }
    }

    /**
     * 展示到用户手机上
     */
    protected void onShowToUser() {
        if (mPresenter == null) {
            return;
        }
        if (isFirstShow) {
            this.isFirstShow = false;
            mPresenter.onFraFirstShow();
        }
        LOG.e("BaseFragment", mPresenter.getClass().getSimpleName() + ".onShowToUser");
//    if (OneFragmentShower.get() != null && OneFragmentShower.get().show2User(this)) {
//      return;
//    }
        if (mPresenter.attach() == null) {
            CtrWatcher.get().addFragmentController(mPresenter);
            CtrWatcher2.get().addFragmentController(mPresenter);
        }
        mPresenter.onControllerResume();
    }

    String fraTag;

    public String getStrTag() {
        if (fraTag == null && mPresenter != null) {
            fraTag = this.getClass().getSimpleName() + ":" + mPresenter.getClass()
                    .getSimpleName() + "-" + System
                    .currentTimeMillis();
        } else if (fraTag == null) {
            fraTag = this.getClass().getSimpleName() + "-" + System.currentTimeMillis();
        }
        return fraTag;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        destoryPresenter();
        LOG.e("BaseFragment", getStrTag() + ".onDetach:" + getTag());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        destoryPresenter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LOG.e("BaseFragment", getStrTag() + ".onDestroy");
        destoryPresenter();
    }

    private void destoryPresenter() {
        if (this.mPresenter != null) {
//      if (OneFragmentShower.get() != null) OneFragmentShower.get().remove(this);
            this.mPresenter.onFragmentDetach();
            CtrWatcher.get().removeWatch(this.mPresenter);
            CtrWatcher2.get().removeWatch(this.mPresenter);
            this.mPresenter = null;
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LOG.e("OnAction", getStrTag() + ".onViewCreated");
        if (fraRoot.findViewById(R.id.common_status_bar) != null) {
            ViewGroup.LayoutParams params = fraRoot.findViewById(R.id.common_status_bar)
                    .getLayoutParams();
            params.height = AppUtils.getStatusBarHeight();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            fraRoot.findViewById(R.id.common_status_bar).setLayoutParams(params);
        }
        mPresenter.onViewCreated(savedInstanceState);
        LOG.d("BaseFragment", "onViewCreated.onShowToUser:");
        onShowToUser();
    }


    //反射获取当前Presenter对象
    protected P getController(Object o, int i) {
        return getController((Class<P>) ((ParameterizedType) (o.getClass().getGenericSuperclass()))
                .getActualTypeArguments()[i]);
    }

    public P getController(Class<P> clazz) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOG.showUserWhere();
        return null;
    }

    //反射获取当前Presenter对象
    public BaseController getController() {
        return mPresenter;
    }

    @Override
    public <T> void handleFailResponse(T baseBean) {

    }

    protected LoadingDialog progressDialog;

    @Override
    public void showLoading(String... msg) {
        if (progressDialog == null) {
            progressDialog = new LoadingDialog(getContext());
//            progressDialog.setCancelable(false);
        }
        if (msg != null && msg.length > 0) {
            progressDialog.setTitle(msg[0]);
        }
        if (!progressDialog.isShowing())
            progressDialog.show();
    }


    @Override
    public void dismissLoading() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    public boolean onBreakPress() {
        if (mPresenter != null) {
            return mPresenter.interruptBack();
        }
        return false;
    }

    BaseController.Operator mOperator;

    public void setOpration(BaseController.Operator operator) {
        this.mOperator = operator;
        if (mPresenter != null) {
            mPresenter.setOperator(operator);
        }
    }

    public boolean isShowToUser() {
        if (mPresenter != null) {
            return mPresenter.isShow();
        }
        return false;
    }

    public boolean isShowProgress() {
        return progressDialog != null && progressDialog.isShowing();
    }
}
